//index.js
const recorderManager = wx.getRecorderManager() //创建录音
const innerAudioContext = wx.createInnerAudioContext() //播放录音
const app = getApp()

Page({
	data: {
		show_textarea: true,
		src: [], //留影图片数组
		liu_ying_data: [], //留影显示于view
		img_count: true, //留影图片数量状态
		video_state: false, //录音开始录音界面/录音完成界面
		impressArr: [{
				title: "高颜值"
			},
			{
				title: "逗比"
			},
			{
				title: "甜"
			},
			{
				title: "大长腿"
			},
			{
				title: "高智商"
			},
			{
				title: "暖"
			},
			{
				title: "乐观"
			},
			{
				title: "腹黑"
			},
			{
				title: "污"
			},
			{
				title: "吃货"
			},
			{
				title: "海王"
			},
			{
				title: "文艺"
			},
		],
		impress_arr: [], //印象标签显示区域
		impress_data: [], //印象显示于view
		tempFilePath: '', //录音路径
		inerval: '', //录音定时器
		video_time_sec: 0, //录音秒时间
		play_inerval: '', //播放定时器
		play_time_sec: 0,
		play_time_min: '00:00',
		waite: true,
		wait_inerval: '',
		wifi_inerval: '',
		start_play: '',
		modalName: '',
		disabled: true,
	},
	onLoad: function (e) {
		// 获取接收者ID
		var that = this
		var member_id = e.member_id
		var share_name = e.share_name
		var headimgurl=e.headimgurl
		console.log("给id为 " + member_id + ",,昵称为 " + share_name + " 的人留言")
		this.setData({
			member_id: member_id,
			share_name:share_name,
			headimgurl:headimgurl,
			text_content: '',
			true_name: '',
			liu_ying_data: [],
			liu_sheng_data: '',
			impress_data: [],
			money_data: '',
		})
		app.createAdv()
		innerAudioContext.onError((res) => {
			console.log('录音播放Error', res)
		})
		innerAudioContext.onPlay(() => {})
		let id = "#textareawrap";
		let query = wx.createSelectorQuery(); //创建查询对象 
		query.select(id).boundingClientRect(); //获取view的边界及位置信息    
		query.exec(function (res) {
			var h = (res[0].height) * 2
			that.setData({
				height: h + "rpx"
			});
		});
	},
	Focus() {},
	onShow() {
		app.showAdv()
	},
	// 返回查看好友页面
	back_check: function () {
		this.stopPlay()
		wx.navigateBack({
			delta: 1
		})
	},
	showModal(e) {
		this.stopPlay()
		var new_src = []
		for (var i = 0; i < this.data.liu_ying_data.length; i++) {
			new_src.push(this.data.liu_ying_data[i])
		}
		var impress_arr = []
		for (var i = 0; i < this.data.impress_data.length; i++) {
			impress_arr.push(this.data.impress_data[i])
		}
		this.setData({
			modalName: e.currentTarget.dataset.target,
			show_textarea: false,
			src: new_src,
			impress_arr: impress_arr,
			money_sum: this.data.money_data,
			money_sums: (this.data.money_datas),
			money_text: this.data.money_data_text,
			play_time_min: '00:00',
			video_state: false,
			start_run: false, //
			video_time_sec: 0,
			disabled: false,
		})

	},
	// 取消弹窗
	hideModal(e) {
		var hideName = e.currentTarget.dataset.target
		if (hideName == 'close2') {
			if (this.data.start_play) {
				this.stopPlay() //停止播放
			}
			if (this.data.start_run) {
				this.stopVideo('close2') //停止录音
			}
		}
		if (hideName == 'close4') {
			this.data.money_sum = false
		}
		this.setData({
			show_textarea: true,
			modalName: null,
			video_time_sec: 0,
			start_play: false,
			money_sum: this.data.money_sum,
			add_text: '', //自定义的文本
			disabled: true,
		})
	},
	// 绑定name的输入框
	bindNameInput: function (e) {
		// this.data.true_name = e.detail.value
		this.setData({
			true_name: e.detail.value
		})
	},
	// 绑定textarea的输入框
	bindTextInput: function (e) {
		this.setData({
			text_content: e.detail.value
		})
	},
	/*
	 * 留影相关操作
	 */
	// 传照片
	uploadPicture: function (e) {
		var that = this
		wx.chooseImage({
			count: 6,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				var src = that.data.src
				if (that.data.src.length <= 6) {
					wx.showLoading({
						title: '图片上传中...',
						mask: true,
					})
					that.setData({
						img_count: true,
					})
					for (var i = 0; i < res.tempFilePaths.length; i++) {
						var imgUrl = res.tempFilePaths[i];
						app.wx_uploadFile('image', imgUrl).then(function (res) {
							that.data.src.push(JSON.parse(res.data).data)
							that.setData({
								src: that.data.src,
								img_count: true
							})
							if (that.data.src) {
								wx.hideLoading()
								wx.showToast({
									title: '上传成功',
									duration: 1000,
									icon: "none",
								})
							}
							if (that.data.src.length == 6) {
								that.setData({
									img_count: false, //控制上传图片+的状态隐藏/显示
								})
							}

						})
					}

				} else {
					return
				}
			},
			fail(err) {}
		})
	},
	// 取消照片
	delPicture: function (e) {
		var that = this
		var index = e.target.dataset.index
		var del_src = that.data.src
		del_src.splice(index, 1)
		that.setData({
			src: del_src
		})
		if (del_src.length < 6) {
			that.setData({
				img_count: true, //控制上传图片+的状态隐藏/显示
			})
		}
	},
	//留影弹窗中照片de完成
	sure1: function () {
		var src = this.data.src
		if (src.length != 0) {
			this.data.liu_ying_data = []
			for (var i = 0; i < src.length; i++) {
				this.data.liu_ying_data.push(src[i])
			}
			// console.log("完成后的图片数据", this.data.liu_ying_data)
			this.setData({
				liu_ying_data: this.data.liu_ying_data,
				one_src: src[0],
				liu_ying_data_sum: this.data.liu_ying_data.length,
				modalName: null,
				show_textarea: true,
			})
		} else {
			this.setData({
				liu_ying_data: [],
				modalName: null,
				show_textarea: true
			})
		}
	},

	/*
	 * 留声相关操作
	 */
	//开始录音的时候
	startVideo: function () {
		var that = this
		that.data.wait_inerval = null
		wx.authorize({
			scope: 'scope.record',
			success(res) {
				that.toVideo() //去录音
			},
			fail(err) {
				wx.showModal({
					title: '提示',
					content: '您未授权录音，功能将无法使用',
					showCancel: true,
					confirmText: "授权",
					confirmColor: "#52a2d8",
					success: function (res) {
						if (res.confirm) {
							wx.openSetting({
								success: (res) => {
									if (!res.authSetting['scope.record']) {
										that.startVideo()
									} else {
										wx.showToast({
											title: '录音功能成功授权',
											duration: 1000,
										})
										that.toVideo() //去录音
									}
								},
								fail: function () {
									console.log("授权设置录音失败");
								}
							})
						} else if (res.cancel) {}
					},
					fail: function () {
						console.log("录音授权fail");
					}
				})
			}
		})
	},
	toVideo() { //授权录音
		var that = this
		that.data.wait_inerval = setInterval(() => {
			that.setData({
				waite: !that.data.waite
			})
		}, 500);
		setTimeout(() => {
			that.setData({
				start_run: true,
			})
		}, 1000);
		const options = {
			duration: 120000, //指定录音的时长，单位 ms
			sampleRate: 16000, //采样率
			numberOfChannels: 1, //录音通道数
			encodeBitRate: 96000, //编码码率
			format: 'mp3', //音频格式，有效值 aac/mp3
			frameSize: 50, //指定帧大小，单位 KB
		}
		//开始录音
		recorderManager.start(options);
		recorderManager.onStart(() => {
			that.data.inerval = null
			var time = 0
			that.data.inerval = setInterval(function () {
				time++
				console.log('录音开始+')
				that.setData({
					video_time_sec: time,
				});
				if (that.data.video_time_sec >= 120) {
					app.wx_modalTip('录音完成', '录音时间最长120s哦~')
					that.stopVideo()
				}
			}, 1000)
		});
		//错误回调
		recorderManager.onError((res) => {
			// recorderManager.stop();
			that.stopVideo('close2')
			console.log("录音错误:", res);
		})
	},
	//停止录音
	stopVideo: function (e) {
		clearInterval(this.data.inerval)
		clearInterval(this.data.wait_inerval)
		var that = this
		recorderManager.stop();
		recorderManager.onStop((res) => {
			if (e == 'close2') {
				console.log("关闭弹窗/录音错误，录音关闭")
				that.setData({
					start_run: false,
					video_state: false,
				})
			} else {
				var res_time = that.data.video_time_sec
				var min = Math.floor(res_time / 60) % 60
				var sec = res_time % 60
				that.setData({
					video_time_sec: res_time,
					video_time_min: ('0' + min + ':' + (sec < 10 ? '0' + sec : sec)),
					tempFilePath: res.tempFilePath,
					waite: true,
					start_run: false,
					video_state: true,
				})
				console.log("录音完成")
			}
		})
	},
	// 在播放录音
	playVideo: function (e) {
		var that = this
		that.setData({
			start_play: !that.data.start_play,
			play_time_min: "00:00"
		})
		innerAudioContext.src = this.data.tempFilePath
		if (that.data.start_play) {
			innerAudioContext.play()
			that.data.play_inerval = null
			var time = 0
			that.data.play_inerval = setInterval(() => {
				time++
				console.log("pop播放+")
				if (time <= that.data.video_time_sec) {
					var min = Math.floor(time / 60) % 60
					var sec = time % 60
					that.setData({
						play_time_min: ('0' + min + ':' + (sec < 10 ? '0' + sec : sec))
					})
					if (time == that.data.video_time_sec) {
						console.log("播放时长到")
						clearInterval(that.data.play_inerval)
						innerAudioContext.stop()
						that.setData({
							start_play: false,
						})
					}
				}
			}, 1000);
		} else {
			this.stopPlay()
		}
	},
	//停止播放
	stopPlay() {
		var that = this
		clearInterval(that.data.wifi_inerval)
		clearInterval(that.data.play_inerval)
		innerAudioContext.stop()
		innerAudioContext.onStop((e) => {})
		that.setData({
			start_play: false,
			play_wifi: false,
			wifi: false,
		})
	},
	wifiVideo: function (e) {
		var that = this
		that.setData({
			play_time_min: "00:00",
			play_wifi: !that.data.play_wifi,
		})
		innerAudioContext.src = this.data.liu_sheng_data
		if (that.data.play_wifi) {
			innerAudioContext.play()
			that.data.wifi_inerval = null
			that.data.wifi_inerval = setInterval(() => {
				that.setData({
					wifi: !that.data.wifi
				})
			}, 400);
			that.data.play_inerval = null
			var time = 0
			that.data.play_inerval = setInterval(() => {
				time++
				console.log("wifi播放+")
				if (time <= that.data.liusheng_sec) {
					var min = Math.floor(time / 60) % 60
					var sec = time % 60
					that.setData({
						play_time_min: ('0' + min + ':' + (sec < 10 ? '0' + sec : sec))
					})
					if (time == that.data.liusheng_sec) {
						console.log("wifi播放时长到")
						clearInterval(that.data.wifi_inerval)
						clearInterval(that.data.play_inerval)
						that.setData({
							play_wifi: false,
							wifi: false,
						})
						innerAudioContext.stop()
					}
				}
			}, 1000);
		} else {
			this.stopPlay()
		}
	},
	wifiClose() {
		this.stopPlay(true)
		this.setData({
			liu_sheng_data: false,
			liusheng_sec: false,
		})
	},
	// 重新录音
	newVideo: function (e) {
		var modalName = e.currentTarget.dataset.target
		this.stopPlay()
		this.setData({
			modalName: modalName,
			show_textarea: false,
			video_state: false,
			video_time_sec: 0,
			play_time_min: '00:00'
		})
	},
	// 完成录音
	finishVideo: function () {
		var that = this
		this.stopPlay()
		var tapingUrl = this.data.tempFilePath //录音路径
		var video_time_min = this.data.video_time_min
		var video_time_sec = this.data.video_time_sec
		app.wx_uploadFile('taping', tapingUrl).then(function (res) {
			that.setData({
				video_state: false,
				video_time_sec: 0,
				liu_sheng_data: JSON.parse(res.data).data,
				liusheng_time_min: video_time_min,
				liusheng_sec: video_time_sec,
				show_textarea: true,
				modalName: null,
			})
		})
	},


	/*
	 * 印象相关操作
	 * 
	 */
	// 选择原有的印象标签
	impressSelect: function (e) {
		var index = e.target.dataset.index
		var impress_arr = this.data.impress_arr
		if (impress_arr.length <= 4) {
			impress_arr.push(this.data.impressArr[index])
			this.setData({
				impress_arr: impress_arr
			})
		} else {
			app.wx_modalTip('只能选择5个哦~', '')
		}
	},
	// 印象标签点击选择/取消
	impressState: function (e) {
		var index = e.target.dataset.index
		var impress_arr = this.data.impress_arr
		impress_arr.splice(index, 1)
		this.setData({
			impress_arr: impress_arr
		})
	},
	// 绑定印象自定义的输入框
	bindKeyInput: function (e) {
		this.data.add_text = e.detail.value
	},
	// 自定义印象+标签
	impressAdd: function () {
		var impress_arr = this.data.impress_arr
		var add_text = this.data.add_text
		if (add_text == '') {
			app.wx_modalTip('自定义标签不能为空哦~', '')
		} else {
			if (impress_arr.length <= 4) {
				impress_arr.push(add_text)
				this.setData({
					impress_arr: impress_arr,
					add_text: ''
				})
			} else {
				app.wx_modalTip('只能选择5个哦~', '')
			}
		}
	},
	sure3: function () {
		var impress_arr = this.data.impress_arr
		this.data.impress_data = []
		for (var i = 0; i < impress_arr.length; i++) {
			this.data.impress_data.push(impress_arr[i])
		}
		this.setData({
			impress_data: this.data.impress_data,
			impress_data_sum: impress_arr.length,
			modalName: null,
			show_textarea: true
		})
	},

	/*
	 * 红包相关操作
	 */
	//绑定红包金额input
	bindMoneySum: function (e) {
		if (e.detail.value > 200) {
			app.wx_modalTip('金额不能大于200哦~', '')
			this.setData({
				money_sum: ''
			})
		} else {
			var money_sum = e.detail.value
			var money_sums = Number(money_sum) + Number(money_sum * 0.02)
			this.setData({
				money_sum: money_sum,
				money_sums: (money_sums).toFixed(2)
			})
		}
	},
	//祝福语
	bindMoneyText: function (e) {
		this.data.money_text = e.detail.value
	},
	//红包支付
	toPay() {
		var money_sum = this.data.money_sum
		if (money_sum) {
			// 手续费后的总金额
			var money_datas = this.data.money_sums
			var money_data_text = this.data.money_text
			this.setData({
				money_data: money_sum,
				money_datas: money_datas,
				money_data_text: money_data_text,
				modalName: null,
				show_textarea: true
			})
		} else {
			app.wx_modalTip('金额不能为空', '请输入金额')
		}
	},

	//去预览
	toPreview: function () {
		var that = this
		wx.setStorageSync('contentArr', '')
		this.stopPlay()
		if (!that.data.text_content) {
			app.wx_modalTip('留言内容不能为空', '请填写留言内容')
		} else if (!that.data.true_name) {
			app.wx_modalTip('姓名不能为空', '请填写姓名')
		} else {
			var contentArr = {
				member_id: that.data.member_id, //接收者id
				sendusername:that.data.share_name, //接收者昵称
				senduserimg:that.data.headimgurl, //接收者头像
				message: that.data.text_content,
				from_name: that.data.true_name,
				photo: that.data.liu_ying_data,
				taping: that.data.liu_sheng_data,
				taping_time: that.data.liusheng_sec,
				impression: that.data.impress_data,
				red_packet: that.data.money_data,
				red_message: that.data.money_data_text
			}
			wx.setStorageSync('contentArr', contentArr)
			// /pages/check-preview/index
			wx.navigateTo({
				url: '/pages/detail/index?kind=' + 'preview'

			})
		}
	},

	onUnload: function () {
		this.stopPlay()
	}
})